#include "FileUtility.h"
#include <QDir>

FileUtility *FileUtility::getInstance()
{
    static FileUtility singleton{};
    return &singleton;
}

QStringList FileUtility::findFile(QString path, QString type)
{
    QDir dir(path);
    QStringList types;

    types.append(type);
    QStringList allFile = QStringList("");
    dir.setFilter(QDir::Files);
    dir.setSorting(QDir::Name);
    allFile = dir.entryList(types);

    return  allFile;
}

int FileUtility::checkUsbDirExist(QString pathname)
{
    QStringList* list = getDirList(pathname);
    QString name;

    if (list->isEmpty())
        return -1;

    for (int i = 0; i < list->size(); i++) {
        name = list->at(i);
        if ((name == "sda") || (name == "sda1") || (name == "sda2") || (name == "sda3")  ||
                (name == "sda4") || (name == "sda5") || (name == "sda6") || (name == "sda7")) {
            qDebug()<<"find usb dir:"<<name;
            return 0;
        }
    }

    return -1;
}

int FileUtility::checkUsbUpdateDirExist(QString pathname)
{
    QStringList* list = getDirList(pathname);
    QString name = " ";

    if (list->isEmpty())
        return -1;

    for (int i = 0; i < list->size(); i++) {
        name = list->at(i);
        if ((name == "sda") || (name == "sda1") || (name == "sda2") || (name == "sda3")  ||
                (name == "sda4") || (name == "sda5") || (name == "sda6") || (name == "sda7")) {
            qDebug()<<"find usb dir:"<<name;
            break;
        }
    }

    QString updatePatch = QString("/run/media/%1/update").arg(name);
    QDir dir;
    if (!dir.exists(updatePatch))
        return -1;

    qDebug()<<"find update patch dir:"<<updatePatch;

    return 0;
}

QStringList* FileUtility::getDirList(QString pathname)
{
    QDir dirinfo;
    static QStringList list;

    list.clear();
    dirinfo.setPath(pathname);

    list = dirinfo.entryList(QDir::Dirs);

    list.removeOne(".");
    list.removeOne("..");

    return &list;
}

FileUtility::FileUtility()
{

}
